package design.masterWorker;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Master {
    // 存放任务队列
    private ConcurrentLinkedQueue<Task> tasksQqueue = new ConcurrentLinkedQueue<>();
    // 存放Worker的Map
    private HashMap<String,Thread> workers = new HashMap<>();
    // 存放每一个Worker的处理结果
    private ConcurrentHashMap<String,Object> taskResultMap = new ConcurrentHashMap<>();

    public Master(Worker worker, int workerCount) {
        worker.setWorkQueue(this.tasksQqueue);
        worker.setTaskResultMap(this.taskResultMap);
        // 将Worker放入容器
        for (int i = 0; i < workerCount; i++) {
            this.workers.put(Integer.toString(i),new Thread(worker));
        }
    }
    // 需要提交一个任务，就是将任务放入到队列中
    public void submit(Task task){
        this.tasksQqueue.add(task);
    }
    // 执行方，启动所有的worker方法去执行任务
    public void execute(){
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            me.getValue().start();
        }
    }
    // 判断是否运行结束的方法
    public boolean isCompelete(){
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            if(me.getValue().getState() != Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }
    // 汇总每个Task的结果
    public int getResult(){
        int priceResult = 0;
        for (Map.Entry<String, Object> me : taskResultMap.entrySet()) {
            priceResult +=(Integer)me.getValue();

        }
        return priceResult;
    }
    public ConcurrentLinkedQueue<Task> getTasksQqueue() {
        return tasksQqueue;
    }

    public void setTasksQqueue(ConcurrentLinkedQueue<Task> tasksQqueue) {
        this.tasksQqueue = tasksQqueue;
    }

    public HashMap<String, Thread> getWorkers() {
        return workers;
    }

    public void setWorkers(HashMap<String, Thread> workers) {
        this.workers = workers;
    }

    public ConcurrentHashMap<String, Object> getTaskResultMap() {
        return taskResultMap;
    }

    public void setTaskResultMap(ConcurrentHashMap<String, Object> taskResultMap) {
        this.taskResultMap = taskResultMap;
    }
}
